package com.example.lenovo.sbns.Activity;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Bundle;
import android.app.Fragment;
import android.os.Handler;
import android.os.Message;
import android.util.AttributeSet;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.ViewFlipper;

import com.avos.avoscloud.AVException;
import com.avos.avoscloud.AVOSCloud;
import com.avos.avoscloud.AVObject;
import com.avos.avoscloud.AVQuery;
import com.avos.avoscloud.FindCallback;
import com.avos.avoscloud.SaveCallback;
import com.example.lenovo.sbns.R;

import org.w3c.dom.Text;

import java.io.IOException;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.lang.String;
import java.util.zip.Inflater;


public class photoPage extends Fragment {

    private Button button1;
    private ListView listView;
    private List<Map<String, Object>> list;
    private MyAdapter myAdapter;



    /**
     * 自动计算ListView高度
     *
     * @param listView
     */
    public static void setListViewHeightBasedOnChildren(ListView listView) {
        //获取ListView对应的Adapter
        ListAdapter listAdapter = listView.getAdapter();
        if (listAdapter == null) {
            // pre-condition
            return;
        }

        int totalHeight = 0;
        System.out.println(listAdapter.getCount());
        for (int i = 0, len = listAdapter.getCount() ; i < len; i++) { //listAdapter.getCount()返回数据项的数目
            View listItem = listAdapter.getView(i, null, listView);
            listItem.measure(0, 0); //计算子项View 的宽高
            totalHeight += listItem.getMeasuredHeight(); //统计所有子项的总高度
        }

        ViewGroup.LayoutParams params = listView.getLayoutParams();
        params.height = totalHeight + listView.getVerticalFadingEdgeLength() * (listAdapter.getCount() / 2 - 1);
        //listView.getDividerHeight()获取子项间分隔符占用的高度
        //params.height最后得到整个ListView完整显示需要的高度
        listView.setLayoutParams(params);
    }


    /**
     * 重写的ListView
     */
    public class MyListView extends ListView {
        public MyListView(Context context, AttributeSet attrs) {
            super(context, attrs);
        }

        public MyListView(Context context) {
            super(context);
        }

        public MyListView(Context context, AttributeSet attrs, int defStyle) {
            super(context, attrs, defStyle);
        }

        @Override
        public void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
            int expandSpec = MeasureSpec.makeMeasureSpec(
                    Integer.MAX_VALUE >> 2, MeasureSpec.AT_MOST);
            super.onMeasure(widthMeasureSpec, expandSpec);
        }
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        System.out.println("07");
        View view = inflater.inflate(R.layout.fragment_photo_page, container, false);
        System.out.println("06");



        button1 = (Button) view.findViewById(R.id.write_self_bt);
        button1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(getActivity(), selfTalk.class);
                startActivity(intent);
            }
        });

        //连接数据库
        AVOSCloud.initialize(getActivity(), "Po6OudEc9QxRgv1qcussxBxi-gzGzoHsz", "EFNsW7y5aXtKMkpU50xyhHNk");

        listView = (ListView) view.findViewById(R.id.fpg_listview);


        /*查询远端数据库数据*/
        final AVQuery<AVObject> query = new AVQuery<>("Talk");
        query.whereEqualTo("prority", 1);
        query.findInBackground(new FindCallback<AVObject>() {
            @Override
            public void done(final List<AVObject> listr, AVException e) {
                List<AVObject> priorityEqualsZeroTodos = listr;// 符合 priority = 1 的 Todo 数组
                final String[] IdLine = new String[priorityEqualsZeroTodos.size()];
                /*动态生成产品表格*/
                list = new ArrayList<Map<String, Object>>();
                /*List数组赋值*/
                for (int i = 0; i < priorityEqualsZeroTodos.size(); i++) {
                    final Map<String, Object> map = new HashMap<String, Object>();
                    final Handler handler = new Handler() {
                        @Override
                        public void handleMessage(Message msg) {
                            map.put("photo", (Drawable) msg.obj);
                            myAdapter = new MyAdapter(list, getActivity());
                            listView.setAdapter(myAdapter);
                            setListViewHeightBasedOnChildren(listView);
                        }
                    };
                    final String url = priorityEqualsZeroTodos.get(i).getString("talkpicture");
                    // image
                    new Thread(new Runnable() {

                        @Override
                        public void run() {
                            //post() is quite important,update pictures in UI main thread
                            Drawable drawable = loadImageFromNetwork(url);
                            Message message = handler.obtainMessage(1, drawable);
                            handler.sendMessage(message);
                        }
                    }).start();  //线程启动
                    map.put("image", priorityEqualsZeroTodos.get(i).get("talkimage"));
                    map.put("declear", priorityEqualsZeroTodos.get(i).getString("talkname"));
                    map.put("time", priorityEqualsZeroTodos.get(i).getString("talktime"));
                    map.put("title", priorityEqualsZeroTodos.get(i).getString("talktitle"));
                    map.put("content", priorityEqualsZeroTodos.get(i).getString("talkcontent"));
                    map.put("talkid",priorityEqualsZeroTodos.get(i).getObjectId());
                    list.add(map);

                    IdLine[i] = priorityEqualsZeroTodos.get(i).getString("objectId");
                    System.out.println("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!"+IdLine[i]);
                }
                for (int i = 0; i < list.size(); i++) {
                    System.out.println(" "+list.get(i));
                }

                /*绑定点击触发器*/
                listView.setOnItemClickListener(
                        new AdapterView.OnItemClickListener() {
                            @Override
                            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                                Intent intent = new Intent();
                                intent.setClass(getActivity(),talk_info.class);
                                intent.putExtra("talkid", list.get(position).get("talkid").toString());
                                System.out.println("###########################################"+(String) list.get(position).get("talkid"));
                                startActivity(intent);
                            }
                        }
                );
            }
        });
        return view;
    }

    /**
     * 数据封装类
     */
    public class ListItem {
        private int Img;
        private String Declear;
        private int Photo;
        private String Title;
        private int Time;
        private String Content;

        public ListItem() {
            super();
        }

        public ListItem(int image, String declear, int photo, int time, String text, String content) {
            Img = image;
            Declear = declear;
            Photo = photo;
            Title = text;
            Time = time;
            Content = content;
        }

        public int getImg() {
            return Img;
        }

        public String getDeclear() {
            return Declear;
        }

        public String getContent() {
            return Content;
        }


        public int getPhoto() {
            return Photo;
        }

        public int getTime() {
            return Time;
        }

        public String getTitle() {
            return Title;
        }

    }

    /**
     * 布局匹配类
     */
    public class ViewHolder {

        public ImageView imageView;
        public TextView declearView;
        public TextView titleview;
        public TextView timeView;
        public ImageView photoView;
        public TextView contentView;

    }

    /**
     * ListView数据适配器
     */
    public class MyAdapter extends BaseAdapter {

        private LayoutInflater layoutInflater;
        private List<Map<String,Object>> list;


        public MyAdapter(List<Map<String, Object>> data, Context context) {
            super();
            layoutInflater = LayoutInflater.from(context);
            list = data;
        }

        @Override
        public int getCount() {
            if (list != null) {
                return list.size();
            } else {
                return 0;
            }
        }

        @Override
        public Object getItem(int position) {
            return list.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            int i = getCount()-position-1;
            ViewHolder viewHolder = new ViewHolder();
            if (convertView == null) {
                convertView = layoutInflater.inflate(R.layout.talk_item, null);
                viewHolder = new ViewHolder();
                viewHolder.imageView = (ImageView) convertView.findViewById(R.id.ImageTag);
                viewHolder.declearView = (TextView) convertView.findViewById(R.id.DeclearTag);
                viewHolder.photoView = (ImageView) convertView.findViewById(R.id.PhotoTag);
                viewHolder.timeView = (TextView) convertView.findViewById(R.id.TimeTag);
                viewHolder.titleview = (TextView) convertView.findViewById(R.id.TextTag);
                //viewHolder.contentView = (TextView) convertView.findViewById(R.id.ContentTag);
                convertView.setTag(viewHolder);
            } else {
                viewHolder = (ViewHolder) convertView.getTag();
            }
            viewHolder.imageView.setImageResource((Integer) list.get(i).get("image"));
            viewHolder.photoView.setImageDrawable((Drawable) list.get(i).get("photo"));
            viewHolder.declearView.setText((String) list.get(i).get("declear"));
            viewHolder.titleview.setText((String) list.get(i).get("title"));
            viewHolder.timeView.setText((String) list.get(i).get("time"));
            return convertView;
        }

    }


    //download image from network using @urladdress
    private Drawable loadImageFromNetwork(String urladdr) {
        // TODO Auto-generated method stub
        Drawable drawable = null;
        try{
            //judge if has picture locate or not according to filename
            drawable = Drawable.createFromStream(new URL(urladdr).openStream(), "image.jpg");
        }catch(IOException e){
            Log.d("test",e.getMessage());
        }
        if(drawable == null){
            Log.d("test","null drawable");
        } else {
            Log.d("test","not null drawable");
        }
        return drawable;
    }

}
